package com.example.cinema.activity;

import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.example.cinema.R;
import com.example.cinema.RequestAuthority;
import com.example.cinema.UserAttribute;
import com.example.cinema.adapter.CircleAdapter;
import com.example.cinema.databinding.ActivityAddcircleBinding;
import com.example.cinema.request.ProgressResponseBody;
import com.example.cinema.request.RequestSend;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

public class ActivityAddCircle extends AppCompatActivity {

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (data.getData() != null && requestCode == IMAGE_TAG) {
            addimagelist(data);
            return;
        }


    }

    private void addimagelist(Intent data) {

        imglist.add(data.getData());
        circleAdapter.notifyDataSetChanged();
    }


    private ActivityAddcircleBinding AAN;
    private UserAttribute attribute;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AAN = DataBindingUtil.setContentView(this, R.layout.activity_addcircle);
        init();
        initlistener();
        attribute = (UserAttribute) getApplication();
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View view = getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View view = getWindow().getDecorView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }
    }


    //图片
    List<Object> imglist = new ArrayList<>();
    CircleAdapter circleAdapter = null;

    private void init() {
        Drawable x = getResources().getDrawable(R.mipmap.upimages);
        imglist.add(x);

        circleAdapter = new CircleAdapter(imglist, getApplicationContext());
        AAN.gridview.setAdapter(circleAdapter);
    }



    private boolean aBoolean = true;
    private void initlistener() {

        //图片列表点击
        AAN.gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    StartAlbum();
                } else {
                    StartAlbum();
                }
            }
        });
        //删掉选中图片
        circleAdapter.setOnImageCloseListener(new CircleAdapter.setOnImageClose() {
            @Override
            public void Close(int positon) {
                if (positon == 0) {
                    return;
                }
                imglist.remove(positon);
                circleAdapter.notifyDataSetChanged();
            }
        });
        //点击发布
        AAN.send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (attribute.getUID() == null || attribute.getToken() == null) {
                    Intent intent = new Intent();
                    intent.setAction("sign");
                    startActivity(intent);
                    return;
                }
                if(aBoolean){
                    aBoolean = false;
                    UpImageRequest();
                }else {
                    Toast.makeText(getApplicationContext(),"正在上传请勿重复操作",Toast.LENGTH_SHORT).show();
                }

            }
        });
        //返回
        AAN.finsh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    //打开相册
    private static final int IMAGE_TAG = 1001;

    private void StartAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, IMAGE_TAG);

    }



    //图片贴上传
    private void UpImageRequest() {
        if (imglist.size() < 2) {
            Toast.makeText(getApplicationContext(), "至少需要2张图片哦", Toast.LENGTH_LONG).show();
        }
        int t = AAN.title.getText().toString().length();
        int c = AAN.centext.getText().toString().length();
        if (t < 2) {
            Toast.makeText(getApplicationContext(), "标题或不能少于5个字符！", Toast.LENGTH_LONG).show();
            return;
        }
        if (c < 10) {
            Toast.makeText(getApplicationContext(), "内容不能少于10个字符！", Toast.LENGTH_LONG).show();
            return;
        }
        String[] poo = {MediaStore.Images.Media.DATA};
        List<File> urllist = new ArrayList<>();
        for (int i = 1; i < imglist.size(); i++) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                Cursor cursor = getContentResolver().query((Uri) imglist.get(i), poo, null, null);
                int cursor_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                String path = cursor.getString(cursor_index);
                File file = new File(path);
                urllist.add(file);
            }
        }
        if (urllist.size() < 2) {
            Toast.makeText(getApplicationContext(), "最少需要2张图片哦！", Toast.LENGTH_LONG).show();
            return;
        }
        String title = AAN.title.getText().toString();
        String cente = AAN.centext.getText().toString();
        if (title.length() > 0 && cente.length() > 0) {
            new Thread() {
                @Override
                public void run() {
                    Log.i("TTTT", "开始上传");
                    boolean b = new RequestSend(getApplicationContext()).CircleSend("img", title, cente, urllist, attribute.getUID());
                    Log.i("TTTT", "上传完毕");
                    aBoolean = true;
                    if (b) {
                        Message message = new Message();
                        message.what = 1000;

                        handler.sendMessage(message);
                        return;
                    }
                    Message message = new Message();
                    message.what = 1001;
                    handler.sendMessage(message);
                    finish();
                }
            }.start();
        }
    }


    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1000) {
                AAN.send.setEnabled(false);
                Toast toast = Toast.makeText(getApplicationContext(), "发布成功待审核", Toast.LENGTH_LONG);
                toast.getView().setBackground(getDrawable(R.drawable.toast_bag));
                toast.getView().setPadding(15, 10, 15, 10);
                TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
                text.setTextColor(Color.BLACK);
                text.setTextSize(14);
                toast.show();
                AAN.title.setText(null);
                AAN.centext.setText(null);
                imglist.clear();
                circleAdapter.notifyDataSetChanged();
                return;
            }
            if(msg.what == 1001){
                AAN.send.setEnabled(false);

                Toast toast = Toast.makeText(getApplicationContext(), "发布失败", Toast.LENGTH_LONG);
                toast.getView().setBackground(getDrawable(R.drawable.toast_bag));
                toast.getView().setPadding(15, 10, 15, 10);
                TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
                text.setTextColor(Color.BLACK);
                text.setTextSize(14);
                toast.show();
                AAN.title.setText(null);
                AAN.centext.setText(null);
                imglist.clear();
                circleAdapter.notifyDataSetChanged();
                return;
            }
        }
    };
}
